package case27

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
	"regexp"
)

func Test() {

	fmt.Println("🎯示例二十七：验证器-基础使用案例")

	r := gin.Default()

	// 注册自定义验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("username", usernameValidator)
		v.RegisterValidation("password", passwordValidator)
	}

	r.POST("/login", func(c *gin.Context) {
		var req RegisterRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "注册成功",
			"data":    req,
		})
	})

	r.Run(":60000")
}

// 用户注册请求结构体
type RegisterRequest struct {
	Username string `json:"username" binding:"required,min=3,max=20,username"`
	Email    string `json:"email" binding:"required,email"`
	Password string `json:"password" binding:"required,min=6,password"`
	Age      int    `json:"age" binding:"required,gte=18"`
}

// 自定义用户名验证器
var usernameValidator validator.Func = func(fl validator.FieldLevel) bool {
	username, ok := fl.Field().Interface().(string)
	if !ok {
		return false
	}
	// 用户名只能包含字母、数字、下划线
	matched := regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString(username)
	return matched
}

// 自定义密码强度验证器
var passwordValidator validator.Func = func(fl validator.FieldLevel) bool {
	password, ok := fl.Field().Interface().(string)
	if !ok {
		return false
	}
	// 密码必须包含至少一个数字和一个字母
	hasNumber := regexp.MustCompile(`[0-9]`).MatchString(password)
	hasLetter := regexp.MustCompile(`[a-zA-Z]`).MatchString(password)
	return hasNumber && hasLetter
}
